package com.ganbo.netty;

import com.ganbo.netty.utils.DateUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @author ganbo
 * @date 2023/1/1 19:03
 */

@Slf4j
public class HelloServer {

    public static void main(String[] args) {

        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);             //处理连接事件线程池
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(1);           //处理io事件线程池
        DefaultEventLoopGroup hsWorkGroup = new DefaultEventLoopGroup(2);   //处理具体io事件里面的耗时操作的线程池

        new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new StringDecoder())
                                .addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        log.info("收到客户端信息:" + msg);
                                        super.channelRead(ctx, msg);
                                    }

                                    @Override
                                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                        log.info("新增一个客户端连接");
                                        super.channelActive(ctx);
                                    }
                                });
                    }
                })
                .bind(8888).addListener(future -> {
            if (future.isSuccess()) {
                log.info("启动成功");
            } else {
                log.info("启动失败");
            }
        });
    }
}
